package com.ts.others.inteceptor;

import cn.hutool.core.bean.BeanUtil;
import com.ts.common.utils.UserContext;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.Map;

import static com.ts.common.constants.RedisConstants.jwt.*;
import static com.ts.common.constants.RedisConstants.jwt.GET_TOKEN;
import static com.ts.common.constants.RedisConstants.jwt.LOGIN_TOKEN_KEY;


@Slf4j
@Component
public class LoginHandlerInterceptor implements HandlerInterceptor {
    private StringRedisTemplate stringRedisTemplate;

    // 由于该类未交给spring管理，因此不能使用自动装配的方式获取RedisTemplate对象
    public LoginHandlerInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(GET_TOKEN);
        log.info("xx处理器的token:{}",token);
        if (token == null || token.isEmpty()) {
            return true;
        }
        Object userIdObj = stringRedisTemplate.opsForHash().get(LOGIN_TOKEN_KEY, token);
        log.info("userIdObj:{}"+userIdObj);
        if(userIdObj==null){
            return true;
        }
        if(UserContext.getUser()==null)
        {

            Long userId = Long.valueOf((String) userIdObj); // 转换为 Long 类型
            log.info("线程池你有没有走啊:{}",userId);
            UserContext.setUser(userId); // 将用户信息放入线程中
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.removeUser();
    }
}